<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <SmForm
      class="-mb-15px"
      ref="formRef"
      isCol
      label-width="150px"
      v-model="formData"
      v-loading="formLoading"
      :options="requestFormOptions"
      :getModelValue="getFormData"
    >
      <template #authTree>
        <el-tree
          ref="permTreeRef"
          node-key="id"
          show-checkbox
          :data="menuTree"
          :filter-node-method="handlePermFilter"
          :check-strictly="false"
          class="mt-5"
          @check="
            (checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys) =>
              (formData.menuIds = checkedKeys?.checkedKeys)
          "
        >
          <template #default="{ data }">
            {{ data.name }}
          </template>
        </el-tree>
      </template>
    </SmForm>

    <template #footer>
      <el-button @click="submitFormDB" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { createUser, getRoleList, getUser, updateUser } from "@/api/user";
import { addProperty } from "@/components/SmForm/src/utils";
import { createDBFn } from "@/utils/decorate";
import { defaultProps, organizationProps } from "@/utils/tree";
import { mockTreeList } from "./data";
import { getDeptTree, getOrganizationList, getUserMenusList } from "@/commonData";
import { useAuth } from "@/views/org/common/hooks/useAuth";
import DeptAPI from "@/api/system/dept-api";
import { terminalTypeList } from "@/commonData/dict";

/** 仓库 表单 */
defineOptions({ name: "OpenForm" });

const { t } = useI18n(); // 国际化

const dialogVisible = ref(false); // 弹窗的是否展示
const dialogTitle = ref(""); // 弹窗的标题
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(""); // 表单的类型：create - 新增；update - 修改
const initFormData = () => {
  return {};
};
const formData: any = ref(initFormData());
const formRef = ref(); // 表单 Ref
const deptTree = ref([]);
const organizationList = ref([]);
// const userMenusList = ref({});

const {
  isExpanded,
  permKeywords,
  checkedRole,
  permTreeRef,
  getMenuTreeAndRoleMenu,
  getMenuTree,
  menuTree,

  setRoleMenu,
  handlePermFilter,
  togglePermTree,
  handleAssignPermSubmit,
} = useAuth();

// 只有选中时才有-调用接口拿到的时候也需要加
// const check = (checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys) => {
//   formData.value.menuIds = checkedKeys?.checkedKeys;
//   // console.log(
//   //   checkedNodes,
//   //   checkedKeys,
//   //   halfCheckedNodes,
//   //   halfCheckedKeys,
//   //   "checkedNodes,checkedKeys,halfCheckedNodes,halfCheckedKeys"
//   // );
// };

const requestFormOptions: any = ref([]);
const createRequestFormOptions = () => {
  // 1、部门名称-name
  // 2、部门编码-code
  // 3、归属机构-orgId
  // 4、上级部门-parentId
  // 5、部门描述-desc
  // 6、权限设置
  // 只有部门描述和权限设置非必填
  //   [
  //     {
  //         "id": "1",
  //         "parentId": "0",
  //         "name": "有来技术",
  //         "code": "YOULAI",
  //         "sort": 1,
  //         "status": 1,
  //         "children": [],
  //         "createTime": null,
  //         "updateTime": "2024-06-24 23:48"
  //     }
  // ]

  /**
    1、menus-关联的菜单
    2、name部门名称
    3、orgNo-所属组织机构编号
    // 4、organization对象-接口详情返回
    // 5、roles-关联的角色 [] 数组-这是详情返回
    6、 sort  排序
    7、terminalType 终端类型：1-能看所有，2-根据出单人显示
   */

  const list = [
    {
      requiredFlag: true,
      type: "input",
      label: "部门名称",
      prop: "name",
      placeholder: "部门名称",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      requiredFlag: true,
      type: "tree-select",
      placeholder: "归属机构",
      // prop: "orgId",
      prop: "orgNo",
      label: "归属机构",
      attrs: {
        filterable: true,
        clearable: true,
        // data: mockTreeList,
        data: organizationList,
        props: organizationProps,
        "check-strictly": true,
        // "node-key": "value",
        // "node-key": "id",
      },
    },
    {
      type: "select",
      placeholder: "终端类型",
      label: "终端类型",
      prop: "terminalType",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: terminalTypeList,
    },

    // 部门就是同级没有有父级，所以这里不需要
    // {
    //   type: "tree-select",
    //   placeholder: "上级部门",
    //   prop: "parentId",
    //   label: "上级部门",
    //   attrs: {
    //     filterable: true,
    //     clearable: true,
    //     data: deptTree,
    //     // props: defaultProps,
    //     "check-strictly": true,
    //     "render-after-expand": false,
    //     // "node-key": "id",
    //   },
    // },
    {
      type: "input-number",
      label: "排序",
      prop: "sort",
      attrs: {
        controls: false,
        clearable: true,
        min: 0,
        precision: 0,
        style: {
          width: "100%",
        },
      },
    },
    {
      type: "input",
      label: "备注",
      prop: "remark",
      placeholder: "备注",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },

    /**
      v1/menus/options
      获取全量 options进行匹配
      获取对应角色的
      v1/roles/2/menuIds
      存储menuIds
     */
    {
      slot: "authTree",
      label: "权限设置",
    },
  ];

  addProperty(list);
  return list;
};

/** 打开弹窗 */
const open = async (type: string, id?: string) => {
  dialogVisible.value = true;
  dialogTitle.value = t("action." + type);
  formType.value = type;
  resetForm();
  getDeptTree(deptTree);
  getOrganizationList(organizationList);
  getMenuTree();
  // getUserMenusList(userMenusList);

  const map: any = {
    create: () => {
      requestFormOptions.value = createRequestFormOptions();
    },
    update: () => {
      requestFormOptions.value = createRequestFormOptions();
    },
  };

  map[type] && map[type]();

  // if (!id) {
  //   getMenuTreeAndRoleMenu();
  // }

  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    try {
      formData.value = await DeptAPI.getFormData(id);
      // formData.value.id = 2; // 模拟数据2有权限数据
      // getMenuTreeAndRoleMenu(formData.value);
      // 主动触发表单数据回显
      formRef.value.initForm();
    } finally {
      formLoading.value = false;
    }
  }
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(["success"]); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as any;
    if (formType.value === "create") {
      await DeptAPI.create(data);
      // ElMessage.success("操作成功");
    } else if (formType.value === "update") {
      await DeptAPI.update(data.id, data);
      // ElMessage.success("操作成功");
    }
    ElMessage.success("操作成功");
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit("success");
  } finally {
    formLoading.value = false;
  }
};
const submitFormDB = createDBFn(submitForm);

/** 重置表单 */
const resetForm = () => {
  formData.value = initFormData();
  formRef.value?.resetFields();
};

const getFormData = () => {
  return formData.value;
};
</script>
